//argv
//0: node
//1: applyPsalmTone.js
//2: GABC-MEDIANT
//3: GABC-TERMINATION
//4: TEXT
//5: {output filename}
//6: {PSALM TITLE}
//i.e. USAGE: node applyPsalmTone.js 'mediantGABC' 'mediant text' 'terminationGABC' 'termination text' 'outputFilename' 'psalmTitle'
var $   = require('jquery'),
    fs  = require('fs'),
    psalmtone = require('./psalmtone.js'),
    mediantGabc = process.argv[2]
    terminationGabc = process.argv[3],
    text = process.argv[4],
    filename = process.argv[5],
    psalmTitle = process.argv[6] || '',
    applyTone = function(mediantGabc,terminationGabc,text,filename,psalmTitle) {
      var lines = text.split('\n');
          mediant = {
            gabc: mediantGabc,
            lang: 'en',
            useOpenNotes: false,
            flexEqualsTenor: true
          },
          termination = {
            gabc: terminationGabc,
            lang: 'en',
            useOpenNotes: false,
            flexEqualsTenor: true
          },
          result = 'centering-scheme: english;\ninitial-style: 0;\ncommentary: '+(psalmTitle)+
          ';\n%mediant: ' + mediantGabc + ';\n%termination: ' + terminationGabc +
          ';\n%%\n(c4)';
      text += '\n\n';
      var extraBreak = false;
      var verseNum = 1;
      result += verseNum + '.() ';
      for(var i = 0; i<lines.length; i+=2) {
        var line = lines[i];
        if(line.match(/^\s*$/)) {
          --i;
          extraBreak = true;
          continue;
        }
        var nextLine = lines[1+i];
        var thirdLine = lines[2+i];
        if(!line.match(/\s\*\s*$/)) {
          line += ' † ' + nextLine;
          nextLine = thirdLine;
          ++i;
        }
        line = line.replace(/\s+\*\s*$/,'');
        // Eventually we will need to perhaps keep track of these numbers when pulling them out.
        line = line.replace(/\[(\d+)\]/,'');
        nextLine = nextLine.replace(/\[(\d+)\]/,'');
        line = line.replace(/([a-z])\|([a-z])/gi,'$1=|$2').replace(/\|+([a-z]+)(\S*)\|+/gi,'$1*$2');
        nextLine = nextLine.replace(/([a-z])\|([a-z])/gi,'$1=|$2').replace(/\|+([a-z]+)(\S*)\|+/gi,'$1*$2');
        
        text += line +'\n' + nextLine + '\n';
        mediant.text = line;
        termination.text = nextLine;
        if(extraBreak) {
          ++verseNum
          extraBreak = false;
          result = result.slice(0,-2) + 'Z)\n' + verseNum + '.() ';
        }
        result += (psalmtone.applyPsalmTone(mediant) + ' *(:) ' + psalmtone.applyPsalmTone(termination)).replace(/\blord\b/ig,'<sc>lord</sc>') + ' (::)\n';
        
      }
      result = result.replace(/\.+\)/g,')');
      fs.writeFileSync('tmp/temp.txt',text);

                  
      if(filename) {
        fs.writeFileSync(filename,result);
      } else {
        console.info(result);
      }
    };
process.exit();